package connect3.team7.util;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import java.io.*;
import java.util.*;
import java.net.*;

import connect3.team7.Player;
import connect3.team7.util.Host;

/*

   Singleton HostController class
   ------------------------------
   - Registers itself with the RMIRegistry

   - Exposes certain methods remotely to client players

*/

public class HostController implements Host {
  private static HostController instance;

  private Registry registry;
  private Host     remoteObj;
  private Host     stub;
  private String   bind_name;

  public static HostController getInstance() {
    if (instance == null)
      instance = new HostController();

    return instance;  
  }

  private HostController() {
    super();
    bind_name = "HostController";
  }

  public void registerHost(int port, Player host) {
    try {
      System.setProperty("java.rmi.server.hostname", IPUtil.getHostIP()); 
      
      registry = LocateRegistry.createRegistry(port);
      
      stub     = (Host) UnicastRemoteObject.exportObject(instance,port); 
      registry.rebind(bind_name, stub);
      System.out.println("HostController registered!");

      DBController db = DBController.getInstance();
      db.insertHost(host);
      System.out.println("Host listing updated!");
    } catch(Exception e) {
      System.err.println("HostController exception: ");
      e.printStackTrace();
    }
  }

  public synchronized boolean join(Player p) {
    String res = null;

    try {
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      System.out.println(p.getName() + " from " + p.getIpAddr() + " is requesting to join!");
      System.out.print("Allow? ");
      res = stdin.readLine();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (res.equals("yes"))
        return true;
      else
        return false;
    }
  }
}
